package com.intracom.activities;

import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import android.content.Context;
import android.content.res.Resources;
import android.content.res.XmlResourceParser;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.intracom.main.R;
import com.intracom.map.layout.MapDataSet;
import com.intracom.map.layout.MapSaxHandler;
import com.intracom.map.layout.RouteOverlay;
import com.intracom.overlay.NEsItemizedOverlay;
import com.intracom.overlay.TLOverlay;


public class NEsMapView extends MapActivity {

	MapView mapView ;
	MapController mController ;
	List<Overlay> mapOverlays;
	
	
	
	
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	@Override
	protected void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		setContentView(R.layout.map_view_layout);
		mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		mController  = mapView.getController();
		mController.setZoom(16);
		mapOverlays =mapView.getOverlays();
		
		GeoPoint geoPoint1 = new GeoPoint((int)(38.02600 * 1e6),(int)(23.81727  * 1e6));
		GeoPoint geoPoint2 = new GeoPoint((int)(38.02600 * 1e6),(int)(23.82727  * 1e6));
		GeoPoint geoPoint3 = new GeoPoint((int)(38.03300 * 1e6),(int)(23.82427  * 1e6));
		GeoPoint geoPoint4 = new GeoPoint((int)(38.01400 * 1e6),(int)(23.81227  * 1e6));
		
		mapOverlays.add(new TLOverlay(geoPoint1 ,geoPoint2));
		
		mapOverlays = mapView.getOverlays();
		mapOverlays.add(new TLOverlay(geoPoint1, geoPoint2));
		mapOverlays.add(new TLOverlay(geoPoint1, geoPoint3));
		mapOverlays.add(new TLOverlay(geoPoint1, geoPoint4));

		NEsItemizedOverlay itemizedOverlay= new NEsItemizedOverlay(getResources().getDrawable(R.drawable.pizzabox_25x25) ,this);
		
		OverlayItem overlayitem1 = new OverlayItem(geoPoint1, "title1", "snippet1");
		itemizedOverlay.addOverlay(overlayitem1);
		
		OverlayItem overlayitem2 = new OverlayItem(geoPoint2, "", "");
		itemizedOverlay.addOverlay(overlayitem2);
		
		OverlayItem overlayitem3 = new OverlayItem(geoPoint3, "", "");
		itemizedOverlay.addOverlay(overlayitem3);
		
		OverlayItem overlayitem4 = new OverlayItem(geoPoint4, "", "");
		itemizedOverlay.addOverlay(overlayitem4);
		mapOverlays.add(itemizedOverlay);

		mController.animateTo(geoPoint1);
		
	}
	
	 
	    public void onCreate_(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.map_view_layout);
			mapView = (MapView) findViewById(R.id.mapview);

	        mapView.setBuiltInZoomControls(true);

	        // Acquire a reference to the system Location Manager
	        LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);

	        String locationProvider = LocationManager.NETWORK_PROVIDER;
	        Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);

    		double latitude  = 38.02600;
    		double longitude = 23.81727;
    		
	        StringBuilder urlString = new StringBuilder();
	        urlString.append("http://maps.google.com/maps?f=d&hl=en");
	        urlString.append("&saddr=");//from
	        urlString.append( Double.toString(latitude ));
	        urlString.append(",");
	        urlString.append( Double.toString(longitude ));
	        urlString.append("&daddr=");//to

	        double[] dest={latitude+100d,longitude+100d};
			urlString.append( Double.toString((double)dest[0]/1.0E6 ));
	        urlString.append(",");
	        urlString.append( Double.toString((double)dest[1]/1.0E6 ));
	        urlString.append("&ie=UTF8&0&om=0&output=kml");

	        try{
	            // setup the url
	            URL url = new URL(urlString.toString());
	            // create the factory
	            SAXParserFactory factory = SAXParserFactory.newInstance();
	            // create a parser
	            SAXParser parser = factory.newSAXParser();
	            // create the reader (scanner)
	            XMLReader xmlreader = parser.getXMLReader();
	            // instantiate our handler
	            MapSaxHandler navSaxHandler = new MapSaxHandler();
	            // assign our handler
	            xmlreader.setContentHandler(navSaxHandler);
	            // get our data via the url class
	            InputStream openRawResource = getResources().openRawResource(R.xml.test2);
	            InputSource is=new InputSource(openRawResource );
	            // perform the synchronous parse           
	            xmlreader.parse(is);
	            // get the results - should be a fully populated RSSFeed instance, or null on error
	            MapDataSet ds = navSaxHandler.getParsedData();

	            // draw path
	            drawPath(ds, Color.parseColor("#add331"), mapView );

	            // find boundary by using itemized overlay

//	            latitude  = 38.02600;
//	    		longitude = 23.82727;
//	    		GeoPoint destPoint = new GeoPoint((int)(latitude * 1e6),(int)(longitude  * 1e6));
//	            GeoPoint currentPoint = new GeoPoint( new Double(lastKnownLocation.getLatitude()*1E6).intValue()
//	                                                ,new Double(lastKnownLocation.getLongitude()*1E6).intValue() );
//
//	            Drawable dot = this.getResources().getDrawable(R.drawable.pizzabox_25x25);
//	            MapItemizedOverlay bgItemizedOverlay = new MapItemizedOverlay(dot,this);
//	            OverlayItem currentPixel = new OverlayItem(destPoint, null, null );
//	            OverlayItem destPixel = new OverlayItem(currentPoint, null, null );
//	            bgItemizedOverlay.addOverlay(currentPixel);
//	            bgItemizedOverlay.addOverlay(destPixel);
//
//	            // center and zoom in the map
//	            MapController mc = mapView.getController();
//	            mc.zoomToSpan(bgItemizedOverlay.getLatSpanE6()*2,bgItemizedOverlay.getLonSpanE6()*2);
//	            mc.animateTo(new GeoPoint(
//	                    (currentPoint.getLatitudeE6() + destPoint.getLatitudeE6()) / 2
//	                    , (currentPoint.getLongitudeE6() + destPoint.getLongitudeE6()) / 2));

	        } catch(Exception e) {
	            Log.d("DirectionMap","Exception parsing kml.");
	        }

	    }
	
	/**
	 * Does the actual drawing of the route, based on the geo points provided in the nav set
	 *
	 * @param navSet     Navigation set bean that holds the route information, incl. geo pos
	 * @param color      Color in which to draw the lines
	 * @param mMapView01 Map view to draw onto
	 */
	public void drawPath(MapDataSet navSet, int color, MapView mMapView01) {

	    Log.d("geoUniMS", "map color before: " + color);        

	    // color correction for dining, make it darker
	    if (color == Color.parseColor("#add331")) color = Color.parseColor("#6C8715");
	    Log.d("geoUniMS", "map color after: " + color);

	    Collection overlaysToAddAgain = new ArrayList();
	    for (Iterator iter = mMapView01.getOverlays().iterator(); iter.hasNext();) {
	        Object o = iter.next();
	        Log.d("geoUniMS", "overlay type: " + o.getClass().getName());
	        if (!RouteOverlay.class.getName().equals(o.getClass().getName())) {
	            // mMapView01.getOverlays().remove(o);
	            overlaysToAddAgain.add(o);
	        }
	    }
	    mMapView01.getOverlays().clear();
	    mMapView01.getOverlays().addAll(overlaysToAddAgain);

	    String path = navSet.getRoutePlacemark().getCoordinates();
	    Log.d("geoUniMS", "path=" + path);
	    if (path != null && path.trim().length() > 0) {
	        String[] pairs = path.trim().split(" ");

	        Log.d("geoUniMS", "pairs.length=" + pairs.length);

	        String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height

	        Log.d("geoUniMS", "lnglat =" + lngLat + ", length: " + lngLat.length);

	        if (lngLat.length<3) lngLat = pairs[1].split(","); // if first pair is not transferred completely, take seconds pair //TODO 

	        try {
	            GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
	            mMapView01.getOverlays().add(new RouteOverlay(startGP, startGP, 1));
	            GeoPoint gp1;
	            GeoPoint gp2 = startGP;

	            for (int i = 1; i < pairs.length; i++) // the last one would be crash
	            {
	                lngLat = pairs[i].split(",");

	                gp1 = gp2;

	                if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
	                        && gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {

	                    // for GeoPoint, first:latitude, second:longitude
	                    gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));

	                    if (gp2.getLatitudeE6() != 22200000) { 
	                        mMapView01.getOverlays().add(new RouteOverlay(gp1, gp2, 2, color));
	                        Log.d("geoUniMS", "draw:" + gp1.getLatitudeE6() + "/" + gp1.getLongitudeE6() + " TO " + gp2.getLatitudeE6() + "/" + gp2.getLongitudeE6());
	                    }
	                }
	                // Log.d("geoUniMS","pair:" + pairs[i]);
	            }
	            //routeOverlays.add(new RouteOverlay(gp2,gp2, 3));
	            mMapView01.getOverlays().add(new RouteOverlay(gp2, gp2, 3));
	        } catch (NumberFormatException e) {
	            Log.e("geoUniMS", "Cannot draw route.", e);
	        }
	    }
	    // mMapView01.getOverlays().addAll(routeOverlays); // use the default color
	    mMapView01.setEnabled(true);
	}

}
